package com.hnhs.aop;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hnhs.info.PageInfo;
import com.hnhs.utils.LocalpageInfoUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component //交给springboot容器
public class PageXAop {
    //定义切入点
    @Pointcut("@annotation(com.hnhs.annotaion.PageX)")
    public void point(){

    }
    //定义环绕通知
    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes=
                RequestContextHolder.getRequestAttributes();
        String pageNum = ((ServletRequestAttributes) requestAttributes)
                .getRequest()
                .getParameter("pageNum");
        String pageSize = ((ServletRequestAttributes) requestAttributes)
                .getRequest()
                .getParameter("pageSize");
        //判断前端是否要求分页
        if (!ObjectUtil.isEmpty(pageNum) && !ObjectUtil.isEmpty(pageSize)){
            PageHelper.startPage(Integer.valueOf(pageNum),
                                 Integer.valueOf(pageSize));
        }
        //从切入点继续执行
        Object value = joinPoint.proceed();
        //判断结果是否为Page类型
        if(value instanceof Page){
            Page page= (Page) value;
            long total = page.getTotal();

            LocalpageInfoUtil.set(PageInfo.builder().total(total).build());
        }

    return value;

    }


}
